package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @ClassName BaidulLocation
 * @Description 百度定位工具类
 * @Author hlj
 * @Date 2023-05-24 20:52
 */
public class BaidulLocationUtil {
    public static String AK = "6RgjztWEAbizhCp1NQ9FlVK0S0W2vY5E";

    //获取地理经纬度
    public static String getLatAndLng(String address) {
        String result = null;
        try {
            BaidulLocationUtil snCal = new BaidulLocationUtil();
            String URL = "https://api.map.baidu.com/geocoding/v3?";
            Map params = new LinkedHashMap<String, String>();
            params.put("address", address);
            params.put("output", "json");
            params.put("ak", AK);
            params.put("callback", "showLocation");
            String s = snCal.requestGetAK(URL, params);

            //从返回结果中，提取经纬度
            result = "";
            String[] split = s.split(":");

            String s1 = split[4].split(",")[0];
            String s2 = split[5].split("}")[0];
            int i1 = s1.lastIndexOf(".");
            String sub1 = s1.substring(0, i1 + 7);
            int i2 = s2.lastIndexOf(".");
            String sub2 = s2.substring(0, i2 + 7);

            result = sub2 + "," + sub1;
        } catch (Exception exception) {
        } finally {
            return result;
        }
    }

    //获取两地距离
    public static Map<String, String> getGap(String origin, String destination) {
        Map<String, String> map = null;
        try {
            String URL = "https://api.map.baidu.com/directionlite/v1/walking?";
            BaidulLocationUtil snCal = new BaidulLocationUtil();
            Map params = new LinkedHashMap<String, String>();
            params.put("origin", origin);
            params.put("destination", destination);
            params.put("ak", AK);
            String jsonGap = snCal.requestGetAK(URL, params);

            map = new HashMap<>();

            JSONObject jsonObject = JSONObject.parseObject(jsonGap);
            String status = jsonObject.getString("status");

            //发生异常情况处理
            if (!"0".equals(status)) {
                //用户地址输入错误
                if (jsonGap.contains("origin or destination is invalid")) {
                    map.put("error", MessageConstant.ADDRESS_BOOK_IS_ERROR);
                    return map;
                } else if (jsonGap.contains("the distance of path must less then 200Km")) {
                    //用户地址超出配送范围
                    map.put("error", MessageConstant.ADDRESS_BOOK_IS_FAR);
                    return map;
                } else {
                    //发生未知异常错误，禁止用户下单，提示网络异常
                    map.put("error", MessageConstant.NETWORK_IS_ERROR);
                }
            }

            //获取距离和时间
            String routes1 = jsonObject.getString("result");
            JSONObject jsonObject1 = JSONObject.parseObject(routes1);
            String routes = jsonObject1.getString("routes");
            JSONObject jsonObject2 = JSONObject.parseObject(routes.substring(1, routes.length() - 1));
            String duration = jsonObject2.getString("duration");
            String distance = jsonObject2.getString("distance");
            map.put("duration", duration);
            map.put("distance", distance);
        } catch (Exception exception) {

        } finally {
            return map;
        }
    }

    //百度自带，装配网址
    public static String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(URLEncoder.encode((String) pair.getValue(),
                    "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
        return buffer.toString();
    }
}
